const { formatTime } = require('./util.js');
const { timeDifference2 } = require('./timeDifference.js');

const day = (timestemp) =>{
  return parseInt(timestemp/(1000*60*60*24));
};
    
//判断订单有没有过期
const queryOrder = function(){
  const db = wx.cloud.database();
  db.collection('orders').orderBy('timestemp','desc').where({
    orderType:'will'
  }).get({
    success: (res) => {
      console.log('[数据库] [查询记录] 成功: ', res.data);
      let orders = res.data;
      let nowTime = formatTime(new Date(new Date().getTime()));
      orders.forEach(v => {
        if(timeDifference2(v.orderTime,nowTime)>15 || day(v.timestemp)<day((new Date()).valueOf()) ){
          //逾期
          db.collection('orders').doc(v._id).update({
            data: {
              orderType: 'timeout'
            },
            success: (result) => {
              console.error('[数据库] [更新记录] 成功：', result);
            },
            fail: (error) => {
              console.error('[数据库] [更新记录] 失败：', error)
            }
          });
        }
      });
    },
    fail: (err) => {
      console.error('[数据库] [查询记录] 失败：', err)
    }
  })
}
module.exports={
  queryOrder,
  day
}